package com.example.service;

import com.example.entity.OrganizationBranch;
import com.example.exception.CustomException;
import com.example.mapper.OrganizationBranchMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组织支部表业务处理
 **/
@Service
public class OrganizationBranchService {

    @Resource
    private OrganizationBranchMapper organizationBranchMapper;

    /**
     * 新增
     */
    public void add(OrganizationBranch organizationBranch) {
        organizationBranchMapper.insert(organizationBranch);
    }

    /**
     * 删除
     */
    @Transactional
    public void deleteById(Integer id) {
        List<OrganizationBranch> sonBranch = organizationBranchMapper.selectByParentId(id);
        if (!CollectionUtils.isEmpty(sonBranch)) {
            OrganizationBranch parentBranch = organizationBranchMapper.selectById(Long.valueOf(id));
            throw new CustomException("支部【" + parentBranch.getBranchName() + "】下还有"
                    + sonBranch.size() + "个子支部，无法删除");
        }
        organizationBranchMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        // 一次性查询所有父子关系
        List<OrganizationBranch> allSonBranches = organizationBranchMapper.selectByParentIds(ids);

        // 检查每个要删除的支部是否有子支部
        if (!CollectionUtils.isEmpty(allSonBranches)) {
            Map<Long, List<OrganizationBranch>> parentToSons = allSonBranches.stream()
                    .collect(Collectors.groupingBy(OrganizationBranch::getParentId));

            // 获取所有要删除的支部信息
            List<OrganizationBranch> parentBranches = organizationBranchMapper.selectByIds(ids);
            Map<Long, String> idToName = parentBranches.stream()
                    .collect(Collectors.toMap(OrganizationBranch::getId, OrganizationBranch::getBranchName));

            // 构建详细的错误信息
            StringBuilder errorMsg = new StringBuilder("以下支部存在子支部，无法删除：\n");
            parentToSons.forEach((parentId, sons) -> {
                errorMsg.append("支部【")
                        .append(idToName.get(parentId))
                        .append("】下有")
                        .append(sons.size())
                        .append("个子支部\n");
            });
            throw new CustomException(errorMsg.toString());
        }

        // 批量删除
        organizationBranchMapper.deleteBatchByIds(ids);
    }


    /**
     * 修改
     */
    public void updateById(OrganizationBranch organizationBranch) {
        organizationBranchMapper.updateById(organizationBranch);
    }

    /**
     * 根据ID查询
     */
    public OrganizationBranch selectById(Integer id) {
        return organizationBranchMapper.selectById(Long.valueOf(id));
    }

    /**
     * 查询所有
     */
    public List<OrganizationBranch> selectAll(OrganizationBranch organizationBranch) {
        return organizationBranchMapper.selectAll(organizationBranch);
    }

    /**
     * 分页查询
     */
    public PageInfo<OrganizationBranch> selectPage(OrganizationBranch organizationBranch, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrganizationBranch> list = organizationBranchMapper.selectAll(organizationBranch);
        return PageInfo.of(list);
    }

    /**
     * 获取领导人管理的支部列表
     */
    public List<OrganizationBranch> getLeaderBranches(Long leaderId, Integer orgType) {
        if (leaderId == null) {
            throw new CustomException("领导人ID不能为空");
        }
        return organizationBranchMapper.selectByLeaderIdAndOrgType(leaderId, orgType);
    }


}